package externalflame.systemdesign.secondkill.dao;


import externalflame.systemdesign.secondkill.entity.Order;
import org.apache.ibatis.annotations.*;

@Mapper
public interface OrderDao {

    @Select("select count(*) from user_purchased where user_id = #{userId} and product_id = #{productId} and seckill_id = #{secKillId}")
    Long findCntByUserId(@Param("userId") Long userId, @Param("productId") Long productId, @Param("secKillId") Long secKillId);

    @Insert("insert into `order` (id, user_id, product_id, num) values (#{order.id}, #{order.userId}, #{order.productId}, #{order.num})")
    void insert(@Param("order") Order order);

    @Update("update stock_info set stock = stock - #{num} where product_id = #{productId} and stock >= #{num} and seckill_id = #{secKillId}")
    int updateStock(@Param("productId") Long productId, @Param("num") Long num, @Param("secKillId") Long secKillId);


    @Select("select count(*) from user_purchased where user_id = #{userId} and product_id = #{productId} and seckill_id = #{secKillId}")
    int hasPerchasedRecord(@Param("userId") Long userId, @Param("productId") Long productId, @Param("secKillId") Long secKillId);

    @Insert("insert into user_purchased (user_id, product_id, num, seckill_id) values (#{userId}, #{productId}, 0, #{secKillId})")
    void insertPurchasedRecord(@Param("userId") Long userId, @Param("productId") Long productId, @Param("secKillId") Long secKillId);

    @Update("update user_purchased set num = num + #{num} where user_id = #{userId} and product_id = #{productId} and num + ${num} <= #{numLimit} and seckill_id = #{secKillId}")
    int updateUserPurchased(@Param("userId") Long userId, @Param("productId") Long productId, @Param("num") Long num, @Param("numLimit") Long numLimit, @Param("secKillId") Long secKillId);
}
